<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  Card as ACard,
  Table as ATable,
  Tag as ATag,
  Button as AButton,
  Image as AImage,
  Popover as APopover,
  Timeline as ATimeline,
  TimelineItem as ATimelineItem,
  message,
  Modal,
} from 'ant-design-vue'
import { EyeOutlined, WarningOutlined } from '@ant-design/icons-vue'
import { getReportedPosts, approveReport, rejectReport } from '@/api/manger'
import { useRouter } from 'vue-router'
import type { TableColumnsType } from 'ant-design-vue'

interface Report {
  reportId: number
  reporterId: number
  reporterName: string | null
  reporterAvatar: string | null
  reason: string
  reportTime: string
  status: number
}

interface ReportedPost {
  postId: number
  title: string
  content: string
  authorId: number
  authorName: string
  authorAvatar: string
  createTime: string
  reportCount: number
  reports: Report[]
}

const router = useRouter()
const loading = ref(false)
const reportedPosts = ref<ReportedPost[]>([])

const columns: TableColumnsType<ReportedPost> = [
  {
    title: '帖子ID',
    dataIndex: 'postId',
    width: 80,
  },
  {
    title: '作者',
    dataIndex: 'authorName',
    width: 120,
  },
  {
    title: '标题',
    dataIndex: 'title',
    width: 150,
  },
  {
    title: '内容',
    dataIndex: 'content',
    ellipsis: true,
    width: 200,
  },
  {
    title: '举报次数',
    dataIndex: 'reportCount',
    width: 100,
    sorter: (a: ReportedPost, b: ReportedPost) => a.reportCount - b.reportCount,
  },
  {
    title: '发布时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '举报详情',
    key: 'reports',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right',
  },
]

const fetchReportedPosts = async () => {
  try {
    loading.value = true
    const res = await getReportedPosts()
    if (res.data.code === 200) {
      reportedPosts.value = res.data.data
    }
  } catch (error) {
    console.error('获取被举报帖子列表失败:', error)
    message.error('获取被举报帖子列表失败')
  } finally {
    loading.value = false
  }
}

const asReportedPost = (record: Record<string, any>): ReportedPost => {
  return record as ReportedPost
}

const handleView = (record: Record<string, any>) => {
  const reportedPost = asReportedPost(record)
  // 将举报信息存储到 localStorage
  localStorage.setItem(
    'tempReportInfo',
    JSON.stringify({
      reportCount: reportedPost.reportCount,
      reports: reportedPost.reports,
    }),
  )

  // 导航到详情页
  router.push({
    path: `/post/${reportedPost.postId}`,
    query: {
      reportInfo: 'true', // 标记这是从举报管理页面来的
    },
  })
}

const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString()
}

const handleApprove = async (post: ReportedPost) => {
  // 获取最新的待处理举报
  const pendingReport = post.reports.find((r) => r.status === 1)
  if (!pendingReport) return

  try {
    const res = await approveReport(pendingReport.reportId, '经审核，该帖子内容符合规范')
    if (res.data.code === 200) {
      message.success('处理成功')
      fetchReportedPosts()
    }
  } catch (error) {
    console.error('处理举报失败:', error)
    message.error('处理举报失败')
  }
}

const handleReject = async (post: ReportedPost) => {
  // 获取最新的待处理举报
  const pendingReport = post.reports.find((r) => r.status === 1)
  if (!pendingReport) return

  Modal.confirm({
    title: '确认处理',
    content: '确定要删除这篇帖子吗？此操作不可恢复。',
    okText: '确定',
    cancelText: '取消',
    okButtonProps: { danger: true },
    async onOk() {
      try {
        const res = await rejectReport(pendingReport.reportId, '经审核，该帖子内容违规')
        if (res.data.code === 200) {
          message.success('处理成功')
          fetchReportedPosts()
        }
      } catch (error) {
        console.error('处理举报失败:', error)
        message.error('处理举报失败')
      }
    },
  })
}

const handleAction = (record: Record<string, any>, action: 'approve' | 'reject') => {
  const post = asReportedPost(record)
  if (action === 'approve') {
    handleApprove(post)
  } else {
    handleReject(post)
  }
}

onMounted(() => {
  fetchReportedPosts()
})
</script>

<template>
  <div class="reported-post">
    <ACard class="statistics-card">
      <div class="statistics">
        <div class="stat-item">
          <WarningOutlined class="warning-icon" />
          <div class="stat-content">
            <span class="stat-number">{{ reportedPosts.length }}</span>
            <span class="stat-label">被举报帖子</span>
          </div>
        </div>
        <div class="stat-item">
          <span class="stat-number">{{
            reportedPosts.reduce((sum, post) => sum + post.reportCount, 0)
          }}</span>
          <span class="stat-label">总举报次数</span>
        </div>
      </div>
    </ACard>

    <ACard class="table-card">
      <ATable
        :columns="columns"
        :data-source="reportedPosts"
        :loading="loading"
        :scroll="{ x: 1200 }"
        :row-key="(record: ReportedPost) => record.postId"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'authorName'">
            <div class="author-cell">
              <AImage
                :src="record.authorAvatar || '/default-avatar.png'"
                :fallback="'/default-avatar.png'"
                :width="32"
                :height="32"
                :preview="false"
                :style="{ borderRadius: '50%' }"
              />
              <span>{{ record.authorName }}</span>
            </div>
          </template>

          <template v-if="column.key === 'reports'">
            <APopover
              title="举报记录"
              trigger="click"
              placement="left"
              :overlayStyle="{ maxWidth: '400px' }"
            >
              <template #content>
                <ATimeline>
                  <ATimelineItem
                    v-for="report in record.reports"
                    :key="report.reportId"
                    :color="report.status === 1 ? 'red' : 'blue'"
                  >
                    <div class="report-item">
                      <div class="reporter-info">
                        <AImage
                          :src="report.reporterAvatar || '/default-avatar.png'"
                          :fallback="'/default-avatar.png'"
                          :width="24"
                          :height="24"
                          :preview="false"
                          :style="{ borderRadius: '50%' }"
                        />
                        <span>{{ report.reporterName || '匿名用户' }}</span>
                      </div>
                      <div class="report-reason">{{ report.reason }}</div>
                      <div class="report-time">{{ formatDate(report.reportTime) }}</div>
                      <div v-if="report.status === 1" class="report-actions">
                        <AButton type="link" @click="handleAction(record, 'approve')">
                          没问题
                        </AButton>
                        <AButton type="link" danger @click="handleAction(record, 'reject')">
                          立即处理
                        </AButton>
                      </div>
                    </div>
                  </ATimelineItem>
                </ATimeline>
              </template>
              <ATag color="red"> {{ record.reportCount }} 次举报 </ATag>
            </APopover>
          </template>

          <template v-if="column.dataIndex === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>

          <template v-if="column.key === 'action'">
            <div class="action-buttons">
              <AButton type="link" @click="handleView(record)">
                <EyeOutlined />
                查看
              </AButton>
              <template v-if="record.reports.some((r) => r.status === 1)">
                <AButton type="link" @click="handleAction(record, 'approve')">没问题</AButton>
                <AButton type="link" danger @click="handleAction(record, 'reject')"
                  >立即处理</AButton
                >
              </template>
            </div>
          </template>
        </template>
      </ATable>
    </ACard>
  </div>
</template>

<style scoped>
.reported-post {
  padding: 24px;
}

.statistics-card {
  margin-bottom: 24px;
}

.statistics {
  display: flex;
  gap: 48px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.warning-icon {
  font-size: 32px;
  color: #ff4d4f;
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #1f1f1f;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.table-card {
  min-height: 500px;
}

.author-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.report-item {
  padding: 8px;
  border-radius: 4px;
  background: #fafafa;
  margin-bottom: 8px;
}

.reporter-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.report-reason {
  color: #1f1f1f;
  margin: 4px 0;
}

.report-time {
  font-size: 12px;
  color: #999;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap; /* 防止按钮换行 */
}

:deep(.ant-timeline-item-content) {
  margin-left: 20px !important;
}

:deep(.ant-table-cell) {
  vertical-align: top;
}

.report-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

:deep(.ant-popover-inner-content) {
  min-width: 300px;
}
</style>
